package com.wisenet.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.DeleteObjectsRequest;
import com.qcloud.cos.model.DeleteObjectsRequest.KeyVersion;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

/**
 * 腾讯云存储工具类
 * @author fzh
 *
 */
public class TencentOssUtil {
	public static Logger logger = Logger.getLogger(TencentOssUtil.class);
	
	private COSClient ossClient;
	private static final String REGION = "ap-guangzhou";
	private static final String BUCKET_NAME = "";
	private static final String SECRET_ID = "";
	private static final String SECRET_KEY = "";
	
	public TencentOssUtil() {
		// 1 初始化用户身份信息(secretId, secretKey)
		COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
		// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
		ClientConfig clientConfig = new ClientConfig(new Region(REGION));
		// 3 生成cos客户端
		ossClient = new COSClient(cred, clientConfig);
	}
	
	/**
	 * 上传图片
	 * @param key
	 * @param contentLength
	 * @param input
	 * @return
	 */
	public String uploadImage(String key, long contentLength, InputStream input) {
		// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
		// 大文件上传请参照 API 文档高级 API 上传
//		File localFile = new File("D:/abc.png");
		// 指定要上传到 COS 上对象键
		// 对象键Key是对象在存储桶中的唯一标识（包含图片后缀名）。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中，对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
		
//		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
		ObjectMetadata objectMetadata = new ObjectMetadata();
		// 设置输入流长度
		objectMetadata.setContentLength(contentLength);
		// 设置 Content type, 默认是 application/octet-stream
		objectMetadata.setContentType("application/octet-stream");
		
		PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, input, objectMetadata);
		try {
			PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
			if (putObjectResult.getETag() != null) {
				String url = "https://fzh-cos-1258302607.cos.ap-guangzhou.myqcloud.com/" + key;
				return url;
			}
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
				}
			}
			destory();
		}
		return null;
	}
	
	/**
	 * 根据key前缀查询object列表
	 * @param prefix
	 * @return
	 */
	public List<COSObjectSummary> listObjects(String prefix) {
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
		// 设置bucket名称
		listObjectsRequest.setBucketName(BUCKET_NAME);
		// prefix表示列出的object的key以prefix开始
		listObjectsRequest.setPrefix(prefix);
		// deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
		listObjectsRequest.setDelimiter("/");
		// 设置最大遍历出多少个对象, 一次listobject最大支持1000
		listObjectsRequest.setMaxKeys(1000);
		
		ObjectListing objectListing = null;
		do {
			try {
		        objectListing = ossClient.listObjects(listObjectsRequest);
		    } catch (Exception e) {
		        return null;
		    }
			String nextMarker = objectListing.getNextMarker();
	        listObjectsRequest.setMarker(nextMarker);
		} while (objectListing.isTruncated());
	    
	    // object summary表示所有列出的object列表
	    return objectListing.getObjectSummaries();
	}
	
	/**
	 * 根据key前缀批量删除object
	 * @param prefix
	 */
	public void deleteObjects(String prefix) {
		// 根据key前缀查询object列表
		List<COSObjectSummary> objectSummaries = listObjects(prefix);
		if (objectSummaries == null || objectSummaries.size() == 0) {
			return;
		}
		List<KeyVersion> kvlist = new ArrayList<>();
		DeleteObjectsRequest delObjsReq = new DeleteObjectsRequest(BUCKET_NAME);
		for (COSObjectSummary objectSummary : objectSummaries) {
	        kvlist.add(new KeyVersion(objectSummary.getKey()));
	    }
		delObjsReq.setKeys(kvlist);
		// 批量删除object
		ossClient.deleteObjects(delObjsReq);
		destory();
	}
	
	/**
	 * 删除文件
	 * @param key = folder + 图片名称 + 后缀.jpg
	 */
	public void deleteFile(String key) {
		ossClient.deleteObject(BUCKET_NAME, key);
		destory();
	}
	
	/**
     * 销毁
     */
    public void destory() {
      ossClient.shutdown();
      logger.info("ossClient shutdown...");
    }
}
